package com.jevons.muffin.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import com.jevons.muffin.R;
import com.jevons.muffin.utilcode.LogUtils;
import com.jevons.muffin.vm.BasePresenter;
import com.jevons.muffin.widget.alertView.AlertView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限申请基类
 * @author linaisheng
 * Created at 2019/4/11.
 */

public abstract class BaseCheckPermissionActivity<P extends BasePresenter> extends BaseActivity<P> {

    private static final int REQUEST_CODE_PERMISSION = 0x901;


    /**
     * 获取需要进行检测的权限数组
     */
    protected abstract String[] getNeedPermissions();

    /**
     * 检测权限
     */
    public boolean checkPermission() {
        //判断android版本号
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        //判断需要的权限中还有那些权限没有背申请
        List<String> needRequestList = getDeniedPermissions(getNeedPermissions());

        if (needRequestList.size() > 0) {
            String[] permissions = needRequestList.toArray(new String[needRequestList.size()]);
            ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_PERMISSION);
            return false;
        }
        return true;
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        if (permissions == null || permissions.length == 0) {
            return needRequestPermissionList;
        }
        for (String permission : permissions) {


            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED) {

                if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                    LogUtils.printError("shouldShowRequestPermissionRationale");
                    needRequestPermissionList.add(permission);
                }
                needRequestPermissionList.add(permission);
            }
        }
        return needRequestPermissionList;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            List<String> notAdoptPermission = new ArrayList<>(); //没有通过的权限
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    notAdoptPermission.add(permissions[i]);
                }
            }
            if (notAdoptPermission.size() == 0) {
                permissionGrantedSuccess();
            } else {
                permissionGrantedFail(notAdoptPermission);
            }
        }
    }

    /**
     * 判断所有权限是否都已授权
     *
     * @return
     */
    protected boolean isGrantedAllPermissions() {
        List<String> needPermissionList = getDeniedPermissions(getNeedPermissions());
        return needPermissionList.size() == 0;
    }

    /**
     * 权限授权成功
     */
    protected abstract void permissionGrantedSuccess();

    /**
     * 权限授权失败
     */
    protected void permissionGrantedFail(List<String> notAdoptPermission){
        showTipsDialog();
    }

    //显示对话框时点击了取消
    protected void cancelStartSettings() {}

    /**
     * 显示提示对话框
     */
    protected void showTipsDialog() {
        new AlertView.Builder(this).setTitle("提示信息").setMessage("应用缺少必要"
                + "权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                .setMessageColor(getResources().getColor(R.color.meta_text_primary))
                .setCancelButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        cancelStartSettings();
                    }
                })
                .setConfirmButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                        finish();
                    }
                }).setCancelable(false).setCanceledOnTouchOutside(false).build().show();
    }

    /**
     * 启动当前应用设置页面
     */
    protected void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

}
